package filter;

import Utils.CookieUtil;
import beans.User;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.net.URLDecoder;

@WebFilter(value = "/*")
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        User existUser = (User)session.getAttribute("existUser");
        if (existUser == null) {
            Cookie[] cookies = req.getCookies();
            Cookie autoLogin = CookieUtil.getCookie(cookies, "autoLogin");
            if (autoLogin!=null) {
                String value = URLDecoder.decode(autoLogin.getValue(), "UTF-8") ;
                User user = JSONUtil.toBean(value, User.class);
                session.setAttribute("existUser",user);
            }
        }
        chain.doFilter(request,response);
    }
}
